<?php

//就近 www.jiujin.me
global $_W, $_GPC;
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
if ($operation == 'display') {
	ca('saoyue.list.view');
	$pindex = max(1, intval($_GPC['page']));
	$psize = 20;
	$list = pdo_fetchall("SELECT * FROM " . tablename('ewei_shop_saoyue') . " WHERE uniacid = '{$_W['uniacid']}' ORDER BY id DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
	foreach($list as $key => $value){
		$list[$key]['lianjie'] = 'http://wx.lanxuevip.com/app/index.php?i=5&c=entry&do=saoyue&m=ewei_shop&id='.$value['id'];
		$list[$key]['datelimit'] = date('Y-m-d',$value['starttime']).' - '.date('Y-m-d',$value['endtime']);
		$record = pdo_fetch("SELECT COUNT(*) AS count FROM " . tablename('ewei_shop_saoyue_record') . " WHERE uniacid = '{$_W['uniacid']}' AND saoyue = '{$value['id']}'");
		$list[$key]['record'] = $record['count'];
		$list[$key]['perlimit'] = $value['perlimit']==0?'无限制':$value['perlimit'];
	}
	$total = pdo_fetchcolumn("SELECT * FROM " . tablename('ewei_shop_saoyue') . " WHERE uniacid = '{$_W['uniacid']}' ORDER BY id DESC");
	$pager = pagination($total, $pindex, $psize);
} elseif ($operation == 'post') {
	$id = intval($_GPC['id']);
	if (empty($id)) {
		ca('saoyue.list.add');
	} else {
		ca('saoyue.list.edit|saoyue.list.view');
	}
	if (checksubmit('submit')) {
		$starttime = strtotime($_GPC['datelimit']['start']);
		$endtime = strtotime($_GPC['datelimit']['end']);
		if ($endtime == $starttime) {
			$endtime = $endtime + 86399;
		}
		$data = array('uniacid' => $_W['uniacid'], 'title' => trim($_GPC['title']), 'num' => trim($_GPC['num']), 'limit' => trim($_GPC['limit']), 'starttime' => $starttime, 'endtime' => $endtime, 'status' => intval($_GPC['status']), 'createtime' => time(), 'perlimit' => intval($_GPC['perlimit']), 'link' => $_GPC['link']);
		if (!empty($id)) {
			pdo_update('ewei_shop_saoyue', $data, array('id' => $id));
			plog('saoyue.list.edit', "修改扫码领余额 ID: {$id}");
		} else {
			pdo_insert('ewei_shop_saoyue', $data);
			$id = pdo_insertid();
			plog('saoyue.list.add', "修改扫码领余额 ID: {$id}");
		}
		message('更新扫码领余额成功！', $this->createWebUrl('saoyue/list', array('op' => 'display')), 'success');
	}
	$time = time();
	$saoyue = pdo_fetch("SELECT * FROM " . tablename('ewei_shop_saoyue') . " WHERE id = '{$id}' and uniacid = '{$_W['uniacid']}'");
	$saoyue['starttime'] = empty($saoyue['starttime']) ? TIMESTAMP : $saoyue['starttime'];
	$saoyue['endtime'] = empty($saoyue['endtime']) ? strtotime('+1 month') : $saoyue['endtime'];
	
} elseif ($operation == 'delete') {
	ca('saoyue.list.delete');
	$id = intval($_GPC['id']);
	$saoyue = pdo_fetch("SELECT id,title  FROM " . tablename('ewei_shop_saoyue') . " WHERE id = '{$id}' AND uniacid=" . $_W['uniacid'] . "");
	if (empty($saoyue)) {
		message('抱歉，扫码领余额不存在或是已经被删除！', $this->createWebUrl('saoyue/list', array('op' => 'display')), 'error');
	}
	pdo_delete('ewei_shop_saoyue', array('id' => $id));
	plog('saoyue.list.delete', "删除扫码领余额 ID: {$id} 标题: {$saoyue['title']}");
	message('扫码领余额删除成功！', $this->createWebUrl('saoyue/list', array('op' => 'display')), 'success');
}elseif ($operation == 'record') {
	$id = intval($_GPC['id']);
	$record = pdo_fetchAll("SELECT *  FROM " . tablename('ewei_shop_saoyue_record') . " WHERE saoyue = '{$id}' AND uniacid=" . $_W['uniacid'] . " order by id desc");
	foreach ($record as $key => $value){
		$record[$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
	}
}elseif ($operation == 'qrcode'){
	$saoyuebox = $_GPC['saoyuebox'];
	$jumpurl = 'http://wx.lanxuevip.com/app/index.php?i=5&c=entry&do=saoyue&m=ewei_shop&id=';
	if (checksubmit('submit')) {
		//print_r($_GPC);exit;
		$saoyuebox = explode(',',$_GPC['saoyuebox']);
		$barcode = array(
			'expire_seconds' => '',
			'action_name' => '',
			'action_info' => array(
				'scene' => array(),
			),
		);
		$acid = intval($_W['acid']);
		$uniacccount = WeAccount::create($acid);
		
		if($_GPC['saoyuebox'] == ''){
			message('抱歉，请先勾选要生成二维码的扫码领余额ID！', $this->createWebUrl('saoyue/list', array('op' => 'display')), 'error');
		}
		//print_r($saoyuebox);exit;
		//批量加入数据库
		foreach ($saoyuebox as $key => $value){
			//ims_rule
			$rule = array(
				'uniacid' 	   => $_W['uniacid'],
				'name'	       => $_GPC['name'].$value,
				'module'       => 'news',
				'displayorder' => 0,
				'status'	   => 1
			);
			pdo_insert('rule', $rule);
			$rid = pdo_insertid();
			//ims_rule_keyword
			$rulekeyword = array(
				'rid'	  	   => $rid,
				'uniacid' 	   => $_W['uniacid'],
				'module'  	   => 'news',
				'content' 	   => $_GPC['keyword'].$value,
				'type'	  	   => 1,
				'displayorder' => 0,
				'status'	   => 1
			);
			pdo_insert('rule_keyword', $rulekeyword);
			//ims_news_reply
			$newsreply = array(
				'rid'	  	   => $rid,
				'parentid' 	   => 0,
				'title'  	   => $_GPC['title'],
				'description'  => $_GPC['description'],
				'thumb'		   => $_GPC['thumb'],
				'content' 	   => '',
				'url'	  	   => $jumpurl.$value,
				'displayorder' => 0,
				'incontent'	   => 1,
				'author'	   => '',
				'createtime'   => TIMESTAMP
			);
			pdo_insert('news_reply', $newsreply);
			//ims_qrcode
			$qrctype = intval($_GPC['qrc-model']);
			if ($qrctype == 1) {
				$qrcid = pdo_fetchcolumn("SELECT qrcid FROM ".tablename('qrcode')." WHERE acid = :acid AND model = '1' ORDER BY qrcid DESC LIMIT 1", array(':acid' => $acid));
				$barcode['action_info']['scene']['scene_id'] = !empty($qrcid) ? ($qrcid+1) : 100001;
				$during = strtotime($_GPC['time']['end']) - strtotime($_GPC['time']['start']);
				$barcode['expire_seconds'] = intval($during);
				$barcode['action_name'] = 'QR_SCENE';
				$result = $uniacccount->barCodeCreateDisposable($barcode);
			} else if ($qrctype == 2) {
				$scene_str = trim($_GPC['scene_str']);
				if(!empty($scene_str)) {
					$barcode['action_info']['scene']['scene_str'] = $scene_str;
					$barcode['action_name'] = 'QR_LIMIT_STR_SCENE';
				} else {
					$qrcid = pdo_fetchcolumn("SELECT qrcid FROM ".tablename('qrcode')." WHERE acid = :acid AND model = '2' ORDER BY qrcid DESC LIMIT 1", array(':acid' => $acid));
					$barcode['action_info']['scene']['scene_id'] = !empty($qrcid) ? ($qrcid+1) : 1;
					if ($barcode['action_info']['scene']['scene_id'] > 100000) {
						message('抱歉，永久二维码已经生成最大数量，请先删除一些。');
					}
					$barcode['action_name'] = 'QR_LIMIT_SCENE';
				}
				$result = $uniacccount->barCodeCreateFixed($barcode);
			}else {
				message('抱歉，此公众号暂不支持您请求的二维码类型！');
			}
			
			if(!is_error($result)) {
				$insert = array(
					'uniacid' => $_W['uniacid'],
					'acid' => $acid,
					'qrcid' => $barcode['action_info']['scene']['scene_id'],
					'scene_str' => $barcode['action_info']['scene']['scene_str'],
					'keyword' => $_GPC['keyword'].$value,
					'name' => $_GPC['title'].$value,
					'model' => $_GPC['qrc-model'],
					'ticket' => $result['ticket'],
					'url' => $result['url'],
					'expire' => $result['expire_seconds'],
					'createtime' => TIMESTAMP,
					'status' => '1',
					'type' => 'scene',
				);
				pdo_insert('qrcode', $insert);
			} else {
				message("公众平台返回接口错误. <br />错误代码为: {$result['errorcode']} <br />错误信息为: {$result['message']}");
			}
			//下载图片了
			//$result['ticket']
		}
		plog('saoyue.list.qrcode', "批量生成二维码 ID 成功: {$saoyuebox}");
		message('批量生成二维码成功！', $this->createWebUrl('saoyue/list', array('op' => 'display')), 'success');
	}
}
load()->func('tpl');
include $this->template('web/saoyue/list');